package entity

import (
	"bytes"
	"errors"
	"fmt"
	"strings"

	"shqsoft.cn/pas3ui/base"

	"gorm.io/gorm"
)

//permissiontype 菜单权限
type MenusType struct {
	ID   string `gorm:"primary_key;column:PermissionType"`
	Name string `gorm:"column:PermissionTypeDes;size:20"`
}

func (MenusType) TableName() string {
	return "t_PermissionType"
}

//Menu 系统菜单
type Menu struct {
	ID             int    `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	No             string `gorm:"column:PermissionNo;size:50"`
	ParentID       int    `gorm:"column:ParentPermissionId"`
	Name           string `gorm:"column:PermissionName;size:50"`
	PermissionType string `gorm:"column:PermissionType;size:50"`
	IsUse          bool   `gorm:"column:ISQY"`
	SortNo         int    `gorm:"column:SortNo"`
	MenusCaptions  string `gorm:"-"`
	ExtendProps    string `gorm:"column:ExtendProps"`
	Icon           string `gorm:"column:Icon"`
	PagePath       string `gorm:"column:pagePath"`
}

func (m *Menu) BeforeCreate(tx *gorm.DB) (err error) {
	var count int64
	err = tx.Model(Menu{}).Where(`"ID"=?`, m.ID).Count(&count).Error
	if err != nil {
		return err
	}
	if count > 0 {
		info := fmt.Sprintf("菜单ID%d已存在，请修改！", m.ID)
		return errors.New(info)
	}
	err = tx.Model(Menu{}).Where(`"PermissionId"=?`, m.No).Count(&count).Error
	if err != nil {
		return err
	}
	if count > 0 {
		info := fmt.Sprintf("菜单编号%s已存在，请修改！", m.No)
		return errors.New(info)
	}
	return
}
func (m *Menu) BeforeUpdate(tx *gorm.DB) (err error) {
	if m.ParentID == 0 {
		return errors.New("默认菜单不允许修改！")
	}
	return
}
func (m *Menu) AfterFind(tx *gorm.DB) (err error) {
	if m.PermissionType != "" {
		ids := strings.Split(m.PermissionType, ",")
		sql := `select PTNM from t_PermissionType where PTID in (?)`
		rows, err := base.MYDB.Raw(sql, ids).Rows()
		if err != nil {
			return err
		}
		var buff bytes.Buffer
		defer rows.Close()
		for rows.Next() {
			var caption string
			rows.Scan(&caption)
			buff.WriteString(caption)
			buff.WriteString(",")
		}
		if l := buff.Len(); l > 0 {
			buff.Truncate(l - 1)
		}
		m.MenusCaptions = buff.String()
	}
	return
}

//TableName Menu 系统菜单表名
func (Menu) TableName() string {
	return "t_Permission"
}
func MenuEF() base.EntityFunc {
	return func() interface{} {
		entity := Menu{}
		return &entity
	}
}
func MenuESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []Menu
		return &entities
	}
}

//permissiontype
func MenusTypeEF() base.EntityFunc {
	return func() interface{} {
		entity := MenusType{}
		return &entity
	}
}
func MenusTypeESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []MenusType
		return &entities
	}
}

func init() {
	base.DaoPoolObj.Put("MenusType", base.NewDefaultDao(MenusTypeEF(), MenusTypeESF(), nil, "my"))
	relationship := []string{"Parent"}
	base.DaoPoolObj.Put("Menu", base.NewDefaultDao(MenuEF(), MenuESF(), relationship, "my"))
}
